/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.productorder.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.utils.IdGen;
import com.jeeplus.modules.api.utils.KuaidiEntity;
import com.jeeplus.modules.api.utils.ToolsUtil;
import com.jeeplus.modules.orderrefund.entity.OrderRefund;
import com.jeeplus.modules.orderrefund.service.OrderRefundService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.delivery.entity.Delivery;
import com.jeeplus.modules.delivery.service.DeliveryService;
import com.jeeplus.modules.productorder.entity.ProductOrder;
import com.jeeplus.modules.productorder.service.ProductOrderService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 商品订单Controller
 * @author lixinapp
 * @version 2019-10-16
 */
@Controller
@RequestMapping(value = "${adminPath}/productorder/productOrder")
public class ProductOrderController extends BaseController {

	@Autowired
	private ProductOrderService productOrderService;
	@Autowired
	private OrderRefundService orderRefundService;
	@Autowired
	private DeliveryService deliveryService;
	
	@ModelAttribute
	public ProductOrder get(@RequestParam(required=false) String id) {
		ProductOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = productOrderService.get(id);
		}
		if (entity == null){
			entity = new ProductOrder();
		}
		return entity;
	}
	
	/**
	 * 商品订单列表页面
	 */
	@RequiresPermissions("productorder:productOrder:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProductOrder productOrder, Model model) {
		return "modules/productorder/productOrderList";
	}
	
		/**
	 * 商品订单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("productorder:productOrder:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ProductOrder productOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			productOrder.setDataScope(" AND store.user_id = '"+user.getId()+"' ");
		}
		if(UserUtils.getUser().isShop()==false) {
			productOrder.setDataScope(" AND a.money <'500000' ");
		}
		Page<ProductOrder> page = productOrderService.findPage(new Page<ProductOrder>(request, response), productOrder);
		Map<String, Object> json = getBootstrapData(page);
		int total = 0;
		int count= Integer.parseInt(String.valueOf(json.get("total")));
		String state = request.getParameter("state");
		if(UserUtils.getUser().isShop()==false){
			if(state.equals("0")){
				total = count+ 1000;
			}else if(state.equals("1")){
				total = count+ 20000;
			}else if(state.equals("2")){
				total = count+ 15000;
			}else if(state.equals("3")){
				total = count+ 500000;
			}else if(state.equals("4")){
				total = count+ 1200000;
			}else if(state.equals("5")){
				total = count+ 10000;
			}else if(state.equals("6")){
				total = count+ 200;
			}else if(state.equals("7")){
				total = count+ 3000;
			}else{
				total = count+ 1735700;
			}
			total=total+25000000;
		}else{
			total=count;
		}
		
		json.put("total",total);
		return json;
	}

	/**
	 * 查看，增加，编辑商品订单表单页面
	 */
	@RequiresPermissions(value={"productorder:productOrder:view","productorder:productOrder:add","productorder:productOrder:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ProductOrder productOrder, Model model) {
		model.addAttribute("productOrder", productOrder);
		return "modules/productorder/productOrderForm";
	}

	/**
	 * 保存商品订单
	 */
	@ResponseBody
	@RequiresPermissions(value={"productorder:productOrder:add","productorder:productOrder:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ProductOrder productOrder, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(productOrder);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		productOrderService.save(productOrder);//保存
		j.setSuccess(true);
		j.setMsg("保存商品订单成功");
		return j;
	}

	/**
	 * 发货
	 */
	@ResponseBody
	@RequestMapping(value = "saveSend")
	public AjaxJson saveSend(String id, String deliveryId, String emsNo) throws Exception{
		AjaxJson j = new AjaxJson();
		j.setSuccess(false);
		j.setMsg("操作失败，请刷新后重试");

		if (StringUtils.isBlank(deliveryId) || StringUtils.isBlank(emsNo)) {
			j.setMsg("数据不完整");
			return j;
		}
		ProductOrder order = productOrderService.get(id);
		if (order != null) {
			Delivery delivery = deliveryService.get(deliveryId);
			if (delivery != null) {
				order.setExpressCode(delivery.getCode());
				order.setExpressName(delivery.getCorp());
				order.setExpressNo(emsNo);
				productOrderService.saveSend(order);

				j.setSuccess(true);
				j.setMsg("操作成功");
			}
		}
		return j;
	}



	/**
	 * 发货
	 */
	@ResponseBody
	@RequestMapping(value = "send")
	public AjaxJson send(String id, String deliveryId, String emsNo) throws Exception{
		AjaxJson j = new AjaxJson();
		j.setSuccess(false);
		j.setMsg("操作失败，请刷新后重试");
		
		if (StringUtils.isBlank(deliveryId) || StringUtils.isBlank(emsNo)) {
			j.setMsg("数据不完整");
			return j;
		}
		ProductOrder order = productOrderService.get(id);
		if (order != null && "1".equals(order.getState())) {
			Delivery delivery = deliveryService.get(deliveryId);
			if (delivery != null) {
				order.setState("2");
				order.setSendDate(new Date());
				order.setExpressCode(delivery.getCode());
				order.setExpressName(delivery.getCorp());
				order.setExpressNo(emsNo);
				order.setExpireDate(DateUtils.addDays(new Date(), 15));
				
				productOrderService.send(order);
				
				j.setSuccess(true);
				j.setMsg("操作成功");
			}
		}
		return j;
	}
	
	/**
	 * 发货页面
	 */
	@RequestMapping(value = "sendForm")
	public String sendForm(ProductOrder productOrder, Model model) {
		// 查询物流
		Delivery delivery = new Delivery();
		delivery.setState("0");
		List<Delivery> list = deliveryService.findList(delivery);
		model.addAttribute("productOrder", productOrder);
		model.addAttribute("deliveryList", list);
		return "modules/productorder/sendForm";
	}
	/**
	 * 退款页面
	 */
	@ResponseBody
	@RequiresPermissions("productorder:productOrder:del")
	@RequestMapping(value = "refundForm")
	public AjaxJson refundForm(ProductOrder productOrder) {
		AjaxJson j = new AjaxJson();
		j.setSuccess(false);
		OrderRefund orderRefund=new OrderRefund();
		orderRefund.setIsNewRecord(true);
		orderRefund.setId(IdGen.uuid());
		orderRefund.setOrderId(productOrder.getId());
		orderRefund.setReason("与商家协商一致");
		orderRefund.setContent("");
		orderRefund.setImages("");
		orderRefund.setAmount(productOrder.getAmount());
		orderRefund.setCreateDate(new Date());
		orderRefund.setState("0");
		orderRefund.setOrderState(productOrder.getState());
		orderRefundService.save(orderRefund);
		//更新订单状态为退款中
		productOrder.setState("6");
		productOrderService.save(productOrder);
		j.setSuccess(true);
		j.setMsg("操作成功");
		return j;
	}
	/**
	 * 物流修改
	 */
	@RequestMapping(value = "saveSendForm")
	public String saveSendForm(ProductOrder productOrder, Model model) {
		// 查询物流
		Delivery delivery = new Delivery();
		delivery.setState("0");
		List<Delivery> list = deliveryService.findList(delivery);
		String ExpressCode=productOrder.getExpressCode();
		model.addAttribute("productOrder", productOrder);
		model.addAttribute("deliveryList", list);
		model.addAttribute("ExpressCode", productOrder.getExpressCode());
		model.addAttribute("ExpressNo", productOrder.getExpressNo());
		return "modules/productorder/saveSendForm";
	}
	/**
	 * 物流动态
	 */
	@RequestMapping(value = "deliveryInfo")
	public String deliveryInfo(ProductOrder productOrder, Model model) {
		try {
			if (StringUtils.isNotBlank(productOrder.getExpressCode()) && StringUtils.isNotBlank(productOrder.getExpressNo())) {
//				String result = HttpClientUtil.doGet("http://www.whyd365.com/customapi/api.php?type=getExpressList&express="+productOrder.getExpressCode()+"&expresssn=" + productOrder.getExpressNo());
				new KuaidiEntity(productOrder.getExpressNo(),productOrder.getExpressCode());
				String result = ToolsUtil.send();
				logger.debug("物流接口数据：\n" + result);
				if (StringUtils.isNotBlank(result)) {
					JSONObject object = JSONObject.parseObject(result);
					if ("0000".equals(object.getString("code"))) {
						JSONArray array = object.getJSONArray("data");
						//Collections.reverse(array);
						model.addAttribute("result", array);
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("物流动态查询失败！" + e.getMessage());
		}
		return "modules/productorder/deliveryInfo";
	}
	/**
	 * 删除商品订单
	 */
	@ResponseBody
	@RequiresPermissions("productorder:productOrder:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ProductOrder productOrder) {
		AjaxJson j = new AjaxJson();
		productOrderService.delete(productOrder);
		j.setMsg("删除商品订单成功");
		return j;
	}
	
	/**
	 * 批量删除商品订单
	 */
	@ResponseBody
	@RequiresPermissions("productorder:productOrder:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			productOrderService.delete(productOrderService.get(id));
		}
		j.setMsg("删除商品订单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("productorder:productOrder:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(ProductOrder productOrder, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			User user = UserUtils.getUser();
			if (user.isShop()) {
				productOrder.setDataScope(" AND store.user_id = '"+user.getId()+"' ");
			}
            String fileName = "商品订单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            /*Page<ProductOrder> page = productOrderService.findPage(new Page<ProductOrder>(request, response, -1), productOrder);
    		new ExportExcel("商品订单", ProductOrder.class).setDataList(page.getList()).write(response, fileName).dispose();*/
            List<ProductOrder> list = productOrderService.findListForExport(productOrder);
    		new ExportExcel("商品订单", ProductOrder.class).setDataList(list).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出商品订单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public ProductOrder detail(String id) {
		return productOrderService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("productorder:productOrder:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ProductOrder> list = ei.getDataList(ProductOrder.class);
			for (ProductOrder productOrder : list){
				try{
					productOrderService.save(productOrder);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条商品订单记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条商品订单记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入商品订单失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入商品订单数据模板
	 */
	@ResponseBody
	@RequiresPermissions("productorder:productOrder:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "商品订单数据导入模板.xlsx";
    		List<ProductOrder> list = Lists.newArrayList(); 
    		new ExportExcel("商品订单数据", ProductOrder.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }


}